//
//  YSSearchCtrl.m
//  Yueshi
//
//  Created by Northwan on 16/1/13.
//  Copyright © 2016年 悦食中国. All rights reserved.
//

#import "YSSearchCtrl.h"
#import "YSCategoryDataTool.h"
#import "YSCategoryHeaderView.h"
#import "YSProductListCtrl.h"
#import "CartView.h"
#import "YSSearchNoResultView.h"
#import "SearchHistoryDao.h"
#import "YSProductListGridItemCell.h"
#import "YSProductDetailCtrl.h"
#import "YSSearchRes.h"
#import "YSSearchProdListView.h"
#import "YSSearchArticleListView.h"
#import "YSSearchProdListCtrl.h"
#import "YSSearchArticleListCtrl.h"

@interface YSSearchCtrl ()<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@property (nonatomic,strong)UITableView *searchTableView;
@property (nonatomic,strong)UISearchBar *searchBar;
@property (nonatomic,strong)UIView *searchBarView;
@property (nonatomic,strong)YSSearchNoResultView *searchNoResult;
@property (nonatomic,strong)UIView *searchView;
@property (nonatomic,assign)float showHeight;
@property (nonatomic,strong)NSMutableArray *searchHistoryArray;
@property (nonatomic,strong)SearchHistoryDao *searchDao;
@property (nonatomic,assign)BOOL isShowFooter;

//@property(nonatomic,strong) UICollectionView *searchCollectionView;
@property (nonatomic, strong) UIScrollView *scrollView;
@property(nonatomic,assign) NSInteger pageIndex;
//@property(nonatomic,strong) NSMutableArray *searchProdArray;

@property (assign,nonatomic) CGFloat currentY;
@end

@implementation YSSearchCtrl

static NSString * const productReuseIdentifier = @"YSProductListItemCell";

//-(NSMutableArray *)searchProdArray{
//    if(!_searchProdArray){
//        _searchProdArray =  [NSMutableArray array];
//    }
//    return _searchProdArray;
//}

- (void)viewDidLoad {
    [super viewDidLoad];

    _searchDao = [[SearchHistoryDao alloc]init];
    _isShowFooter = YES;
    
    _showHeight =   SCREENH-NavWithStatusBarH;
    
    _searchView = [[UIView alloc]init];
    _searchView.hidden = YES;
    [_searchView setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:_searchView];
    
    _searchView.frame = CGRectMake(0, 0, SCREENW, SCREENH-NavWithStatusBarH);
    
    //初始化搜索view
    [self initSearchView];
}

-(void)initSearchView{
    //添加搜索
    UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, SCREENW, 30)];
    [searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"searchbar_textfield_background"] forState:UIControlStateNormal];
    searchBar.delegate = self;
    searchBar.placeholder = @"搜索";
    [searchBar setBackgroundColor:[UIColor clearColor]];
    [searchBar setBarTintColor:[UIColor whiteColor]];
    [searchBar setKeyboardType:UIKeyboardTypeDefault];
    [searchBar setTintColor:ThemeColor];
    [searchBar setValue:@(0) forKeyPath:@"_background.alpha"];
    _searchBar = searchBar;
    
    if (iOS8) {
        self.navigationItem.titleView = _searchBar;
    }else{
        _searchBarView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, 30)];
        [_searchBarView addSubview:_searchBar];
        self.navigationItem.titleView = _searchBarView;
    }
    
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, _showHeight) style:UITableViewStyleGrouped];
    [tableView setBackgroundColor:HEXColor(@"#eaeae9")];
    [tableView setSectionFooterHeight:30];
    
    UIView *header = [UIView new];
    [header setFrame:CGRectMake(0, 0, SCREENW, 0.1)];
    [tableView setTableHeaderView:header];
    [tableView setSeparatorColor:HEXColor(@"#d4d4d4")];
    [tableView setDelegate:self];
    [tableView setDataSource:self];
    
    UIView *footerView = [UIView new];
    [footerView setBackgroundColor:[UIColor clearColor]];
    [tableView setTableFooterView:footerView];
    [_searchView addSubview:tableView];
    _searchTableView = tableView;
    
//    [self initSearchCollectionView];
    [self initSearchScrollView];
}

- (void)initSearchScrollView{
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, _showHeight)];
    [_scrollView setAlwaysBounceVertical:YES];
    [_scrollView setDelegate:self];
    [_scrollView setHidden:YES];
    [_scrollView setUserInteractionEnabled:YES];
    [_searchView addSubview:_scrollView];
}

//-(void)initSearchCollectionView{
//    UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc]init];
//    [flowLayout setMinimumLineSpacing:5];
//    [flowLayout setMinimumInteritemSpacing:5];
//    
//    UICollectionView *collectionView  =[[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, _showHeight) collectionViewLayout:flowLayout];
//    [collectionView setBackgroundColor:HEXColor(@"#eaeae9")];
//    [collectionView registerClass:[YSProductListGridItemCell class] forCellWithReuseIdentifier:productReuseIdentifier];
//    
//    [collectionView setDelegate:self];
//    [collectionView setDataSource:self];
//    [collectionView setAlwaysBounceVertical:YES];
//    [collectionView registerNib:[UINib nibWithNibName:productReuseIdentifier bundle: [NSBundle mainBundle]] forCellWithReuseIdentifier:productReuseIdentifier];
//    [_searchView addSubview:collectionView];
//    [collectionView setHidden:YES];
//    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(searchHeaderRefresh)];
//    collectionView.header = header;
//    collectionView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(searchFooterRefresh)];
//    self.searchCollectionView = collectionView;
//}
//
//-(void)searchHeaderRefresh{
//    self.pageIndex = 0;
//    [self requestSearchDataWithKeyWords:_searchBar.text];
//}
//
//-(void)searchFooterRefresh{
//    self.pageIndex ++;
//    [self requestSearchDataWithKeyWords:_searchBar.text];
//}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (_scrollView.hidden) {
        [_searchBar becomeFirstResponder];
    }
}

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    if ([_searchTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_searchTableView setSeparatorInset:UIEdgeInsetsMake(0,YSPublicXInset,0,0)];
    }
    
    if ([_searchTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_searchTableView setLayoutMargins:UIEdgeInsetsMake(0,YSPublicXInset,0,0)];
    }
}

#pragma mark - searchbar代理方法
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    [_searchTableView setHidden:NO];
    [_searchNoResult setHidden:YES];
    searchBar.placeholder = @"请输入商品名称";
    _searchHistoryArray = [NSMutableArray arrayWithArray:[_searchDao selectAllData]];
    [_searchTableView reloadData];
    [searchBar setShowsCancelButton:YES animated:NO];
    
    for(UIView *view in  [[[searchBar subviews] objectAtIndex:0] subviews]) {
        if([view isKindOfClass:[NSClassFromString(@"UINavigationButton") class]]) {
            UIButton * cancel =(UIButton *)view;
            [cancel.titleLabel setFont:SYS_FONT(15)];
            [cancel setTitle:@"取消" forState:UIControlStateNormal];
            [cancel setTitleColor:ThemeColor forState:UIControlStateNormal];
        }
    }
    
    if (iOS7) {
        searchBar.width = SCREENW;
    }
    
    _searchView.hidden = NO;
    
    return true;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    /*
    _isShowFooter = YES;
    searchBar.placeholder = @"搜索";
    [searchBar resignFirstResponder];
    [searchBar setText:@""];
    [searchBar setShowsCancelButton:NO animated:YES];
    _searchView.hidden = YES;
    
    if (iOS7) {
        searchBar.width = kSearchBarWidth;
    }

    [_searchProdArray removeAllObjects];
    [_searchCollectionView reloadData];
    _searchCollectionView.hidden = YES;*/
    [self hideKeyWordsWithHideCancle];
    dispatch_after(0.25, dispatch_get_main_queue(), ^{
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    });
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    _pageIndex = 0;
    [self requestSearchDataWithKeyWords:searchBar.text];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    _isShowFooter = NO;
    if(ISBLANK(searchText)) return;
    [YSCategoryDataTool searchThinkKeysWithParam:searchText success:^(SearchThinkKeys *result) {
        NSLog(@"返回结果：%@",result.thinkKeys);
        if(result.thinkKeys){
            [_searchHistoryArray removeAllObjects];
            [_searchHistoryArray addObjectsFromArray:result.thinkKeys];
            [_searchTableView reloadData];
        }
        
        if (!self.scrollView.hidden) {
            self.scrollView.hidden = YES;
            [self clearSubviews];
        }
    } failure:^(NSError *error) {
        if (!self.scrollView.hidden) {
            self.scrollView.hidden = YES;
            [self clearSubviews];
        }
    }];
}


#pragma mark <UICollectionViewDataSource>
//- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
//    return self.searchProdArray.count;
//}
//
//- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
//
//        YSProductListGridItemCell *cell = [YSProductListGridItemCell cellWithCollectionView:collectionView indexPath:indexPath];
//        [cell setProd:self.searchProdArray[indexPath.row]];
//        return cell;
//}
//
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//
//        return CGSizeMake((SCREENW-25)/2, 250);
//}
//
//- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//    NSLog(@"indexpath.row=%ld",(long)indexPath.row);
//    NSInteger prodId = [self.searchProdArray[indexPath.row] prodId];
//    YSProductDetailCtrl *ctrl =  [[YSProductDetailCtrl alloc]initWithProdId:prodId];
//    [self.navigationController pushViewController:ctrl animated:YES];
//}
//
//-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
//    return UIEdgeInsetsMake(10,10,10,10);
//}

#pragma mark - UIScrollView delegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self hideKeyWordsWithHideCancle];
}

#pragma mark - TableView 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if(_isShowFooter){
        return 2;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(section){
        if(_searchHistoryArray.count){
            return 1;
        }
    }else{
        return _searchHistoryArray.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    [cell setBackgroundColor:HEXColor(@"#eaeae9")];
    if(!indexPath.section){
        cell.imageView.image = [UIImage imageNamed:@"search_history_icon"];
        cell.textLabel.textColor = publicTextColor;
        cell.textLabel.textAlignment = NSTextAlignmentLeft;
        //反转做倒序显示
        cell.textLabel.text = _searchHistoryArray[_searchHistoryArray.count - 1 - indexPath.row];
        return cell;
    }else{
        cell.imageView.image = nil;
        cell.textLabel.textColor = publicTextColor;
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.textLabel.text = @"清除历史记录";
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section){
        //点击了清除历史记录
        [_searchDao deleteAllHistory];
        [_searchHistoryArray removeAllObjects];
        [tableView reloadData];
    }else{
        //点击了条目，这个地方去请求数据
        [self requestSearchDataWithKeyWords:_searchHistoryArray[_searchHistoryArray.count-1 - indexPath.row]];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - 请求搜索数据
-(void)requestSearchDataWithKeyWords:(NSString *)keyWords{
    _searchTableView.hidden = YES;
//    _searchCollectionView.hidden = NO;
    _scrollView.hidden = NO;
    if(ISBLANK(keyWords)) return;
    [_searchDao addKeyWords:keyWords];
    self.searchBar.text = keyWords;
//    [YSCategoryDataTool searchProductDataWithKeyWords:keyWords pageIndex:_pageIndex success:^(ProductSearch *result) {
//        [self searchCollectionViewComplete];
//        if (result.isSucc) {
//            [_searchNoResult setHidden:YES];
//            if(_pageIndex == 0){
//                [_searchProdArray removeAllObjects];
//            }
//            [_searchProdArray addObjectsFromArray:result.productList];
//            [_searchCollectionView reloadData];
//            [self hideKeyWordsWithHideCancle];
//            
//            if(!_searchProdArray.count){
//                [self showNullResultView];
//            }
//        }else{
//            _searchCollectionView.hidden = YES;
//            [self hideKeyWordsWithHideCancle];
//        }
//    } failure:^(NSError *error) {
//        _searchCollectionView.hidden = YES;
//        [self searchCollectionViewComplete];
//        [self hideKeyWordsWithHideCancle];
//    }];
    
    [YSCategoryDataTool searchDataWithKeywords:keyWords searchType:0 pageIndex:_pageIndex success:^(YSSearchRes *result) {
        if (result.isSucc) {
            [_searchNoResult setHidden:YES];
            [self hideKeyWordsWithHideCancle];
            [self dealData:result];
            
            if (result.productList.count == 0 && result.reviews.count == 0) {
                [self showNullResultView];
            }
        }else{
            [self hideKeyWordsWithHideCancle];
        }
    } failure:^(NSError *error) {
        _scrollView.hidden = YES;

        [self hideKeyWordsWithHideCancle];
    }];
}

-(void)clearSubviews{
    NSArray *subviews = self.scrollView.subviews;
    for (UIView *subview in subviews) {
        if([subview isKindOfClass:[YSSearchArticleListView class]]
           ||
           [subview isKindOfClass:[YSSearchProdListView class]]){
            [subview removeFromSuperview];
        }
    }
    self.currentY = 0;
}

-(void)dealData:(YSSearchRes *)result{
    if (result.productList.count == 0 && result.reviews.count == 0) {
        _scrollView.hidden = YES;
        return;
    }
    
    [self clearSubviews];
    
    if (result.productList.count) {
        YSSearchProdListView *prodListView = [[YSSearchProdListView alloc] init];
        [prodListView setY:self.currentY];
        [self.scrollView addSubview:prodListView];
        [prodListView setArray:result.productList];
        self.currentY = CGRectGetMaxY(prodListView.frame);
        [prodListView setMoreClick:^{
            [self.navigationController pushViewController:[[YSSearchProdListCtrl alloc] initWithData:result.productList keywords:self.searchBar.text] animated:YES];
        }];
    }
    
    if (result.reviews.count) {
        YSSearchArticleListView *articleListView = [[YSSearchArticleListView alloc] initWithY:self.currentY];
        [articleListView setY:self.currentY];
        [self.scrollView addSubview:articleListView];
        [articleListView setArray:result.reviews];
        self.currentY = CGRectGetMaxY(articleListView.frame);
        articleListView.moreClick = ^{
            [self.navigationController pushViewController:[[YSSearchArticleListCtrl alloc] initWithData:result.reviews keywords:self.searchBar.text] animated:YES];
        };
    }
    
    NSLog(@"current maxY = %f  current ScreenH = %f",self.currentY,SCREENH);
    [_scrollView setContentSize:CGSizeMake(SCREENW, self.currentY)];
    NSLog(@"contentSize = %f",self.scrollView.contentSize.height);
}

#pragma mark -注销第一响应者，并且隐藏取消
-(void)hideKeyWordsWithHideCancle{
    [_searchBar resignFirstResponder];
//    [_searchBar setShowsCancelButton:NO animated:YES];
    
    //因为searchBar失去焦点之后，cancle按钮也会失去焦点,在失去焦点之后主动把cancle设置enabled为YES也是一种解决办法,缺点是每次都需要遍历子控件
    for(UIView *view in  [[[_searchBar subviews] objectAtIndex:0] subviews]) {
        if([view isKindOfClass:[NSClassFromString(@"UINavigationButton") class]]) {
            UIButton * cancel =(UIButton *)view;
            cancel.enabled = YES;
        }
    }
}

//-(void)searchCollectionViewComplete{
//    if(_searchCollectionView){
//        [_searchCollectionView.header endRefreshing];
//        [_searchCollectionView.footer endRefreshing];
//    }
//}

#pragma mark -显示末搜索到结果的页面
-(void)showNullResultView{
    if (_searchNoResult==nil) {
        _searchNoResult = [[YSSearchNoResultView alloc]init];
        _searchNoResult.x = (_searchView.width-_searchNoResult.width)/2;
        _searchNoResult.y = (_searchView.height-_searchNoResult.height)/2;
        [_searchView addSubview:_searchNoResult];
        _searchNoResult.hidden = YES;
    }
    _searchTableView.hidden = YES;
    _searchNoResult.hidden = NO;
//    _searchCollectionView.hidden = YES;
    _scrollView.hidden = YES;
}

@end
